package org.bluweb.g4wicket.gadget;

import java.util.HashMap;
import java.util.Map;

import org.apache.wicket.Component;
import org.apache.wicket.Page;
import org.apache.wicket.behavior.SimpleAttributeModifier;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.model.Model;
import org.apache.wicket.util.template.PackagedTextTemplate;
import org.apache.wicket.util.template.TextTemplate;

public abstract class Gadget<T extends GadgetContent> extends Page {

	private Map<String,String> modulePreferences = new HashMap<String, String>();
	private final Component modulePrefs = new Label( "modulePrefs" );
	
	protected Gadget() {
		
		this.add( modulePrefs );

		this.add( new Label( "cdata_start", new Model<String>( "<![CDATA[" ) ).setRenderBodyOnly( true ).setEscapeModelStrings( false ) );
		this.add( new Label( "cdata_end", new Model<String>( "]]>" ) ).setRenderBodyOnly( true ).setEscapeModelStrings( false ) );
		
		String name = this.getClass().getName();
		name = name.substring( name.lastIndexOf( "." ) + 1 );
		TextTemplate template = new PackagedTextTemplate( this.getClass(), name + ".js" );
		
		this.add( new Label( "script", new Model<String>( template.asString() ) ).setEscapeModelStrings( false ) );
		
		this.add( this.getContent() );
	}

	protected abstract T getContent();
	
	@Override
	public String getMarkupType() {
	    return "xml";
	}
	
	public void setTitle( String title ) {
		this.modulePreferences.put( "title", title );
	}
	
	public void setTitleUrl( String url ) {
		this.modulePreferences.put( "title_url", url );
	}
	
	public void setDescription( String description ) {
		this.modulePreferences.put( "description", description );
	}
	
	public void setAuthor( String author ) {
		this.modulePreferences.put( "author", author );
	}

	public void setAuthorEmail( String authorEmail ) {
		this.modulePreferences.put( "author_email", authorEmail );
	}

	public void setScreenshotUrl( String screenshotUrl ) {
		this.modulePreferences.put( "screenshot", screenshotUrl );
	}

	public void setThumbnailUrl( String thumbnailUrl ) {
		this.modulePreferences.put( "thumbnail", thumbnailUrl );
	}
	
	@Override
	protected void onBeforeRender() {
		super.onBeforeRender();
		for( String name : this.modulePreferences.keySet() ) {
			this.modulePrefs.add( new SimpleAttributeModifier( name, this.modulePreferences.get( name ) ) );
		}
	}
}
